/*
 * Copyright © 2017 eqxiu.com 北京中网易企秀科技有限公司  All rights reserved.
 */

package cn.hermit.doclet;

import com.sun.javadoc.Doclet;
import com.sun.javadoc.LanguageVersion;
import com.sun.javadoc.RootDoc;
import com.sun.tools.doclets.formats.html.HtmlDoclet;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author JackGao 高建国
 * @description //TODO 设计说明
 * @date 5/6/2017
 */
public class HermitDoclet extends Doclet {

    public static boolean start(RootDoc root) {
        Map<String, String> optionMap = parse(root.options());
        String docGeneratorHashcode = optionMap.get("docGenerator");
        DocGenerator generator = null;
        if (docGeneratorHashcode == null) {
            generator = new HtmlDocGenerator();
        } else {
            generator = generatorCacheMap.get(docGeneratorHashcode);
        }
        if (generator == null) {
            generator = new HtmlDocGenerator();
        }
        try {
            generator.generate(root);
        } finally {
            if (docGeneratorHashcode != null) {
                generatorCacheMap.remove(docGeneratorHashcode);
            }
        }
        return true;
    }


    public static int optionLength(final String option) {
        Integer length = OPTIONS.get(option);
        return length == null ? HtmlDoclet.optionLength(option) : length;
    }

    public static LanguageVersion languageVersion() {
        return LanguageVersion.JAVA_1_5;
    }

    //key object hashcode
    private static ConcurrentMap<String, DocGenerator> generatorCacheMap = new ConcurrentHashMap<>();

    private static final Map<String, Integer> OPTIONS = new HashMap<>();

    static {
        OPTIONS.put("-sourcepath", 2);
        OPTIONS.put("-doclet", 2);
        OPTIONS.put("-docGenerator", 2);
    }

    public static void addToCache(String hashcode, DocGenerator generator) {
        generatorCacheMap.put(hashcode, generator);
    }

    public static void removeFromCache(String hashcode) {
        generatorCacheMap.remove(hashcode);
    }

    private static void clearCache() {
        generatorCacheMap.clear();
    }

    public static Map<String, String> parse(String[][] options) {
        Map<String, String> optionMap = new LinkedHashMap<>();
        if (options == null || options.length == 0) {
            return optionMap;
        }
        for (String[] option : options) {
            if (option.length == 1) {
                optionMap.put(option[0].substring(1), "true");
            } else if (option.length == 2) {
                optionMap.put(option[0].substring(1), option[1]);
            }
        }
        return optionMap;
    }
}
